package com.company.test.sync;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 一道面试题：实现一个容器，提供两个方法，add,size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，
 * 线程2给出提示并结束
 * <p>
 * 这里虽然T2能够及时收到消息唤醒，但是wait会释放锁，notify不会释放锁，所以T1线程结束后
 * T2线程才执行完成
 */
public class ConcurrentDemo1 {
    List<Object> list = new ArrayList<>();

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        Object lock = new Object();
        ConcurrentDemo1 demo1 = new ConcurrentDemo1();

        new Thread(
                () -> {
                    synchronized (lock) {
                        System.out.println("t2启动");
                        if (demo1.size() != 5) {
                            try {
                                System.out.println("休眠");
                                lock.wait();
                                System.out.println("唤醒" + System.currentTimeMillis());
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                        System.out.println("t2结束");
                    }
                }, "t2").start();

        new Thread(
                () -> {
                    synchronized (lock) {
                        for (int i = 0; i < 1000; i++) {
                            demo1.add(new Object());
                            System.out.println("add " + i);
                            if (demo1.size() == 5) {
                                lock.notify();
                                System.out.println("开始唤醒" + System.currentTimeMillis());
                            }
                            try {
                                TimeUnit.SECONDS.sleep(1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, "t1").start();

    }

}
